package ruifeng.zcj.dig.base.baidumap;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.radar.RadarNearbyResult;
import com.baidu.mapapi.radar.RadarSearchError;
import com.baidu.mapapi.radar.RadarSearchListener;
import com.baidu.mapapi.radar.RadarSearchManager;
import com.baidu.mapapi.radar.RadarUploadInfo;
import com.baidu.mapapi.radar.RadarUploadInfoCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import ruifeng.zcj.dig.R;

/***
 * RadarSearchManager.getInstance().setUserID(userID); 上传用户信息 上传uid 上传坐标
 *
 **/
public class BaiduMapActivity extends Activity implements BDLocationListener, OnClickListener, OnCheckedChangeListener,
		RadarUploadInfoCallback, RadarSearchListener, OnMarkerClickListener, OnMapClickListener {
	// 地图控件
	private MapView mMapView;
	// 地图控制对象
	private BaiduMap mBaiduMap;
	// 定位客户端
	private LocationClient locationClient;
	// 判断是否第一次定位
	private boolean isFirstLoc = true;
	// 总页数，当前页码
	private int currPage = 0;

	private LatLng latLng;
	private boolean uploadAuto = false;

	private Button baidu_signIn;

	private BDLocation location;

	private String permissionInfo;
	private final int SDK_PERMISSION_REQUEST = 127;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SDKInitializer.initialize(getApplicationContext());

		setContentView(R.layout.baidumap);

		getPersimmions();
		// 初始化View
		initViews();

		// 获取对地图的控制
		mBaiduMap = mMapView.getMap();

		// 初始化定位的默认设置
		// 1.打开定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 2.设置默认的定位显示模式
		// 参数1：显示模式；参数2：是否显示方向；参数3：自定义图标，null表示使用默认图标
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(LocationMode.NORMAL, true, null));
		// 初始化定位客户端
		initLocationClinet();
		// 开始定位
		locationClient.start();
		// 监听定位结果回调
		locationClient.registerLocationListener(this);

	}

	private void initViews() {
		mMapView = (MapView) findViewById( R.id.mMapView);
		baidu_signIn = (Button) findViewById( R.id.baidu_signIn);
		baidu_signIn.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		int i = view.getId();
		if (i ==  R.id.baidu_signIn) {
			updateData();
			// Toast.makeText(getApplicationContext(), "打卡成功", 1).show();

		} else {
		}
	}

	/***
	 * 提交到服务器
	 **/
//	public void UpdataDataServer(Map<String, String> map) {
//		int ygxxId = sharePre.getInt("ygxxId");
//		String url = ConstantsUrl.forget_interface + ConstantsUrl.clocksUser + "ygxxId=" + ygxxId + "&yhdkAddress="
//				+ map.get("address") + "&wd=" + map.get("dLat") + "&jd=" + map.get("dLon");
//		// System.out.println("打卡"+url);
//		httpUtils = new HttpUtils();
//		xHandler = httpUtils.send(HttpMethod.POST, url, new RequestCallBack<String>() {
//			@Override
//			public void onFailure(HttpException arg0, String arg1) {
//
//			}
//
//			@Override
//			public void onSuccess(ResponseInfo<String> responseinfo) {
//				// TODO Auto-generated method stub
//				User user = AnalyzeJson.parseLogin(responseinfo.result);
//				if (user.getCode().equals("0000")) {// 登录成功
//
//					Toast.makeText(getApplicationContext(), "打卡成功", Toast.LENGTH_SHORT).show();
//
//				} else if (user.getCode().equals("1111")) {// 用户名或者密码错误
//					Toast.makeText(getApplicationContext(), "" + user.getResult(), 1).show();
//				} else if (user.getCode().equals("0001")) {// 用户输入有吴
//					Toast.makeText(getApplicationContext(), "" + user.getResult(), 1).show();
//				}
//
//			}
//		});
//
//	}

	/** 定位成功标识 */
	private final int LOCATION_SUCCESS = 1;
	/** 定位失败标识 */
	private final int LOCATION_ERROR = 0;
	/** 定位操作处理 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
				case LOCATION_SUCCESS:
					Map<String, String> map = (HashMap<String, String>) msg.obj;
				/*
				 * 	map.put("city", city);
					map.put("address", address);
					map.put("time", location.getTime());
				*/
					String address=map.get("city");
					String city=map.get("address");
					String time=map.get("time");
//				StringBuilder add = null;
//				add.append(city).append(address);
				/*
				 * baidu_signIn.setText("dLat:" + map.get("dLat") + "\n" +
				 * "dLon:" + map.get("dLon") + "\n" + "city:" + map.get("city")
				 * + "\n" + "address:" + map.get("address"));
				 */
//				发送数据到服务器
//				UpdataDataServer(map);

//				Toast.makeText(getApplicationContext(), "打卡成功", 1).show();
					finish();
					break;

				case LOCATION_ERROR:
					Toast.makeText(getApplicationContext(), "请稍后再试", Toast.LENGTH_SHORT).show();
					break;
			}
		}

	};

	/**
	 * 上传更新数据
	 ***/
	private void updateData() {
		if (location != null) {
			String city = "";
			String address = "";
			city = location.getCity();
			address = location.getAddrStr();
//			double dLat = location.getLatitude();// 纬度
//			double dLon = location.getLongitude();
			Message msg = handler.obtainMessage();
			if (city == null) {
				msg.what = LOCATION_ERROR;
				msg.sendToTarget();
			} else {
				int end = city.indexOf("市");
				if (end != -1) {
					city = city.substring(0, end);
				}
				end = address.indexOf("市");
				if (end != -1) {
					address = address.substring(end + 1, address.length());
				}
				Map<String, String> map = new HashMap<String, String>();
//				map.put("dLat", "" + dLat);
//				map.put("dLon", "" + dLon);
				map.put("city", city);
				map.put("address", address);
				map.put("time", location.getTime());
				msg.what = LOCATION_SUCCESS;
				msg.obj = map;
				msg.sendToTarget();
			}

		} else {
			Message msg = handler.obtainMessage();
			msg.what = LOCATION_ERROR;
			msg.sendToTarget();
		}
	}

	// 定位结果回调
	@Override
	public void onReceiveLocation(BDLocation location) {
		this.location = location;
		// 定位的纬度
		double latitude = location.getLatitude();
		// 经度
		double longitude = location.getLongitude();


		final String locationCity = location.getCity();
		final String templeCityCode = location.getCityCode();
		System.out.println("郑朝军"+locationCity);
		System.out.println("郑朝军"+templeCityCode);
		// 在地图中显示定位结果
		// 定位的坐标
//		Log.e("baidu", location.getAddrStr() + "===大道==="
//				+  location.getTime());
		latLng = new LatLng(latitude, longitude);
		// 定位的精度
		float radius = location.getRadius();
		// 配置定位的数据
		MyLocationData locationData = new MyLocationData.Builder().accuracy(radius).latitude(latitude)
				.longitude(longitude).build();
		mBaiduMap.setMyLocationData(locationData);

		if (isFirstLoc) { // 第一次定位需要配置定位的坐标缩放等状态

			// 创建更新地图的对象，配置坐标和缩放级别
			MapStatusUpdate update = MapStatusUpdateFactory.newLatLngZoom(latLng, 15);
			// 更新地图的定位信息
			mBaiduMap.setMapStatus(update);
			isFirstLoc = false;
		}
	}

	private void initLocationClinet() {

		// getApplicationContext():创建的对象具有和应用一样的生命周期，
		// 只有当应用退出的时候，对象才会销毁
		locationClient = new LocationClient(getApplicationContext());
		// 定位客户端的option
		LocationClientOption option = new LocationClientOption();
		// 设置定位的模式：1.高精度 2.低功耗 3.仅设备
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
		// 定位坐标，bd0911为百度定位坐标
		option.setCoorType("bd09ll");
		// 定位间隔时间，单位是毫秒
		option.setScanSpan(3000);
		// 是否显示地址
		option.setIsNeedAddress(true);
		// 是否打开GPS
		option.setOpenGps(true);
		// 为定位客户端设置option
		locationClient.setLocOption(option);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		// 当应用退出时，停止或销毁地图的一些对象
		mMapView.onDestroy();
		locationClient.stop();

		// 释放周边雷达相关
		RadarSearchManager.getInstance().removeNearbyInfoListener(this);
		RadarSearchManager.getInstance().clearUserInfo();
		RadarSearchManager.getInstance().destroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
		mMapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
		mMapView.onPause();
	}

	@Override
	public void onCheckedChanged(RadioGroup arg0, int checkId) {

	}

	@Override
	public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub
		mBaiduMap.hideInfoWindow();
	}

	@Override
	public boolean onMapPoiClick(MapPoi arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onGetClearInfoState(RadarSearchError arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetNearbyInfoList(RadarNearbyResult error, RadarSearchError arg1) {
		// TODO Auto-generated method stub
		/*
		 * if (error == RadarSearchError.RADAR_NO_ERROR) {
		 * Toast.makeText(RadarDemo.this, "查询周边成功", Toast.LENGTH_LONG) .show();
		 * //获取成功 listResult = result; curPage = result.pageIndex; totalPage =
		 * result.pageNum; //处理数据 parseResultToList(listResult);
		 * parseResultToMap(listResult); clearRstBtn.setEnabled(true); } else {
		 * //获取失败 curPage = 0; totalPage = 0; Toast.makeText(RadarDemo.this,
		 * "查询周边失败", Toast.LENGTH_LONG) .show(); }
		 */
	}

	@Override
	public void onGetUploadState(RadarSearchError error) {
		// TODO Auto-generated method stub
		if (error == RadarSearchError.RADAR_NO_ERROR) {
			// 上传成功
			if (!uploadAuto) {
				Toast.makeText(getApplicationContext(), "单次上传位置成功", Toast.LENGTH_LONG).show();
			}
		} else {
			// 上传失败
			if (!uploadAuto) {
				Toast.makeText(getApplicationContext(), "单次上传位置失败", Toast.LENGTH_LONG).show();
			}
		}
	}

	// 自动上传
	@Override
	public RadarUploadInfo onUploadInfoCallback() {
		RadarUploadInfo info = new RadarUploadInfo();
		info.comments = "郑朝军";
		info.pt = latLng;
		return info;
	}



	@TargetApi(23)
	private void getPersimmions() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			ArrayList<String> permissions = new ArrayList<String>();
			/***
			 * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
			 */
			// 定位精确位置
			if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
				permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
			}
			if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
				permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
			}
			/*
			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
			// 读写权限
			if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
				permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
			}
			// 读取电话状态权限
			if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
				permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
			}

			if (permissions.size() > 0) {
				requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
			}
		}
	}

	@TargetApi(23)
	private boolean addPermission(ArrayList<String> permissionsList, String permission) {
		if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
			if (shouldShowRequestPermissionRationale(permission)){
				return true;
			}else{
				permissionsList.add(permission);
				return false;
			}

		}else{
			return true;
		}
	}

	@TargetApi(23)
	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);

	}
}
